package com.jintu.portal.service.datadriver.parser;

import com.jintu.portal.service.datadriver.parser.impl.*;
import com.jintu.portal.utils.ApplicationContextHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * @author very
 */
@Slf4j
@Component
public class DataParserGetter {

    public enum Parser {
        CARRIER_PARSER(new String[]{"carrier"}, CarrierParser.class),
        TAOBAO_PARSER(new String[]{"taoBao", "taoBaoSelf", "taoBaoPartner"}, TaoBaoParser.class),
        IDCARD_AND_MOBILE_CHECK_PARSER(new String[]{"idCardCheckNoPhoto", "mobileCheckAll"}, IdCardAndMobileCheckParser.class),
        MOBILE_ONLINE_PARSER(new String[]{"mobileOnline"}, MobileOnlineParser.class),
        ZM_SCORE_PARSER(new String[]{"zmScore"}, ZmScoreParser.class),
        GONG_JI_JIN_PARSER(new String[]{"gongJiJin"}, GongJiJinParser.class),
        SHE_BAO_PARSER(new String[]{"shebao"}, SheBaoParser.class),
        WANG_YIN(new String[]{"wangyin"}, WangYinParser.class),
        DUO_TOU_PARSER(new String[]{"duoTou"}, DuoTouParser.class),
        XUE_XIN_PARSER(new String[]{"xuexin"}, XueXinParser.class),
        ZHI_FU_BAO_PARSER(new String[]{"zhifubao"}, ZhiFuBaoParser.class);

        private String[] dataSourceCodes;
        private Class<? extends DataParser> beanClass;

        Parser(String[] dataSourceCode, Class<? extends DataParser> beanClass) {
            this.dataSourceCodes = dataSourceCode;
            this.beanClass = beanClass;
        }

        public String[] getDataSourceCodes() {
            return dataSourceCodes;
        }

        public Class getBeanClass() {
            return beanClass;
        }

        public static Parser getDataParserByDataSourceCode(String dataSourceCode) {
            if (StringUtils.isBlank(dataSourceCode)) {
                return null;
            }
            for (Parser p : Parser.values()) {
                if (ArrayUtils.contains(p.getDataSourceCodes(), dataSourceCode)) {
                    return p;
                }
            }
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    public DataParser getDataParser(String paramDataSourceCode) {
        Parser parser = Parser.getDataParserByDataSourceCode(paramDataSourceCode);
        if (parser == null) {
            log.error("无法从【{}】数据源中获取该数据源的解析器。", paramDataSourceCode);
            return null;
        }
        return (DataParser) ApplicationContextHelper.getBean(parser.getBeanClass());
    }
}
